<template>
  <div>
    <el-container>
      <el-header>
        <h2>添加讲师</h2>
      </el-header>
      <el-main>
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="讲师名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="讲师等级" prop="level">
            <el-select v-model="form.level" placeholder="请选择">
              <el-option label="高级讲师" value="1" selected></el-option>
              <el-option label="首席讲师" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="讲师资历" prop="career">
            <el-input v-model="form.career"></el-input>
          </el-form-item>
          <el-form-item label="讲师简介" prop="intro">
            <el-input type="textarea" :rows="5" v-model="form.intro"></el-input>
          </el-form-item>
          <el-form-item label="讲师头像" prop="avatar">
            <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import {teacherAddCols} from "@/views/edu/cols";
import {tableMixin} from "@/components/PageTable/mixin";

export default {
  name: "add",
  mixins: [tableMixin],
  data() {
    return {
      list: [],
      cols: teacherAddCols,
      uploadUrl: window.config.baseUrl + "/oss-service/file/upload",
      form: {
        name: "",
        level: "1",
        intro: "",
        career: "",
        sort: 0, // 排序
        avatar: "", // 头像
      },
      rules: {
        name: [{required: true, message: "请输入名称", trigger: "blur"}],
        career: [{required: true, message: "请输入资历信息", trigger: "blur"}],
        intro: [{required: true, message: "请输入简介信息", trigger: "blur"}]
      },
      updateId: "", // 待更新的ID
      imageUrl: ''
    };
  },
  watch: {
    $route: {
      immediate: true,
      handler(v) {
        if (!v.query.id) {
          this.reset();
        }
      }
    }
  },
  created() {
    this.updateId = this.$route.query.id;
    if (this.updateId) {
      this.findById();
    }
  },
  methods: {
    reset() {
      this.form = {
        name: "",
        level: "1",
        intro: "",
        career: "",
        sort: 0, // 排序
        avatar: "", // 头像
      };
      this.imageUrl = '';
    },
    onSubmit() {
      this.$refs.form.validate((flag) => {
        if (flag) {
          if (this.updateId) {
            this.updateTeacher();
          } else {
            this.addTeacher();
          }
        }
      });
    },
    addTeacher() {
      this.$api.api_edu.addTeacher(this.form).then((res) => {
        if (res.success) {
          this.$message.success("添加成功");
          this.$router.push({path: "/eduTeacher/list"});
        }
      });
    },
    updateTeacher() {
      this.$api.api_edu.updateTeacher(this.form).then((res) => {
        if (res.success) {
          this.$message.success("更新成功");
          this.$router.push({path: "/eduTeacher/list"});
        }
      });
    },
    findById() {
      this.$api.api_edu.findById(this.updateId).then((res) => {
        let data = (res.data && res.data.data && res.data.data[0]) || {};
        this.form = data;
        this.imageUrl = this.form.avatar;
      });
    },
    handleAvatarSuccess(res, file) {
      this.form.avatar = res.data && res.data.path || '';
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      let allowType = ['image/png', 'image/jpeg', 'image/jpg'];
      const isAllow = allowType.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 20;

      if (!isAllow) {
        this.$message.error('上传头像图片只能是 png/jpg 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!');
      }
      return isAllow && isLt2M;
    }
  },
};
</script>

<style scoped>
.avatar-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader >>> .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 64px;
  height: 64px;
  line-height: 64px;
  text-align: center;
}

.avatar {
  width: 64px;
  height: 64px;
  display: block;
}
</style>